//
//  ECMemberCommonSearchViewModel.m
//  ECERP.CRM
//
//  Created by 刘思麟 on 2018/11/5.
//  Copyright © 2018 Mac. All rights reserved.
//

#import "ECMemberCommonSearchViewModel.h"
#import "GLHTTPTool.h"

#define limit 20
@interface ECMemberCommonSearchViewModel ()

@property (nonatomic,assign) NSInteger page;

@end
extern NSString * merchantId;
@implementation ECMemberCommonSearchViewModel

- (instancetype)init {
    if (self = [super init]) {
        self.page = 1;
    }
    return self;
}

- (void)fetchData {
    [GLHTTPTool getWithURL:self.url params:@{@"page":@"1",@"limit":@(INT_MAX),@"merchantId":merchantId} success:^(id json) {
        if ([json[@"code"] integerValue] == 0){
            NSArray * arr = [NSArray modelArrayWithClass:[ECMemberCommonSearchModel class] json:json[@"data"]];
            BOOL haveMore = YES;
            if (arr.count < limit){
                haveMore = NO;
            }
            NSDictionary * dataDic = @{@"haveMore":@(haveMore),@"data":arr};
            if (self.returnBlock) {
                self.returnBlock(dataDic);
            }
        }else{
            if (self.errorBlock) {
                self.errorBlock(json[@"msg"]);
            }
        }
    } failure:^(NSError *error) {
        if (self.failureBlock) {
            self.failureBlock(error);
        }
    }];
}

- (void)loadMore {
    [GLHTTPTool getWithURL:self.url params:@{@"page":@(self.page+1),@"limit":@(INT_MAX),@"merchantId":merchantId} success:^(id json) {
        if ([json[@"code"] integerValue] == 0){
            NSArray * arr = [NSArray modelArrayWithClass:[ECMemberCommonSearchModel class] json:json[@"data"]];
            BOOL haveMore = YES;
            if (arr.count >= limit) {
                self.page += 1;
            }else{
                haveMore = NO;
            }
            NSDictionary * dataDic = @{@"haveMore":@(haveMore),@"data":arr};
            if (self.returnBlock) {
                self.returnBlock(dataDic);
            }
        }else{
            if (self.errorBlock) {
                self.errorBlock(json[@"msg"]);
            }
        }
    } failure:^(NSError *error) {
        if (self.failureBlock) {
            self.failureBlock(error);
        }
    }];
}

@end
